<?php
namespace app\index\controller;

use app\index\model\CompanyModel;
use app\index\model\DealcomModel;
use app\index\model\DeptModel;
use app\index\model\EnginModel;
use app\index\model\FlowBillModel;
use app\index\model\FlowClassModel;
use app\index\model\FlowCourseModel;
use app\index\model\FlowFactorModel;
use app\index\model\FlowLogModel;
use app\index\model\FlowPromerModel;
use app\index\model\FlowSetModel;
use app\index\model\FlowShareModel;
use app\index\model\FlowTalkModel;
use app\index\model\FlowTaskModel;
use app\index\model\FlowTaskShenModel;
use app\index\model\LoginListModel;
use app\index\model\LoginTokenModel;
use app\index\model\LogListModel;
use app\index\model\MenuButModel;
use app\index\model\MenuModel;
use app\index\model\OptionModel;
use app\index\model\UserGangModel;
use app\index\model\UserModel;
use app\index\model\UserRoleModel;
use app\index\model\UserTakeListModel;
use app\index\model\UserTakeModel;
use app\index\service\EnginService;
use app\index\service\FlowService;
use app\index\service\MenuService;
use app\index\service\OptService;
use app\index\service\UserService;
use think\Db;
use think\Request;

class User extends Common
{

    public function list_company(Request $request){
        $data = $this->cominfo;
        $data['comnum'] = $data['comnum'] > 0 ? $data['comnum'] : '不限制';
        $data['usernums'] = $data['usernum'] > 0 ? $data['usernum'] : '不限制';
        $data['capacitys'] = '不限制';
        if($data['capacity'] > 0){
            $data['capacitys'] = round($data['capacity']/1024/1024, 2);
        }

        if(empty($data['enddt']) || $data['enddt'] == '0000-00-00'){
            $data['enddts'] = $data['startdt'].' 至 '.'永久';
        }else{
            $data['enddts'] = $data['startdt'].' 至 '.$data['enddt'];
        }

        return outputJson(2000,lang('code_2000'),$this->cominfo);
    }

    public function can_company(Request $request){
        if($request->isPost()) {
            $param = $request->post();



            Db::startTrans();
            try {
                if(isset($param['issingle'])){
                    CompanyModel::where(['id'=>$this->cominfo['id']])->update(['issingle'=>$param['issingle']]);
                }
                if(isset($param['isqian'])){
                    CompanyModel::where(['id'=>$this->cominfo['id']])->update(['isqian'=>$param['isqian']]);
                }



                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data['issingle'] = $this->cominfo['issingle'];
            $data['isqian'] = $this->cominfo['isqian'];
            $data['isqianarr'] = [0=>'否',1=>'是',2=>'仅手机端'];
            $data['butauth'] = (new MenuService())->get_butauth('company_can');
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function pei_company(Request $request){
        if($request->isPost()){
            $param = $request->post();

            unset($param['token']);


            $param['man_created_user'] = $this->userinfo['id'];
            $param['man_created_at'] = date('Y-m-d H:i:s');

            Db::startTrans();
            try {
                CompanyModel::where(['id'=>$this->userinfo['comid']])->update($param);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data['man_created_user'] = UserModel::get_realname_by_pk($this->cominfo['man_created_user']);
            $data['man_created_at'] = $this->cominfo['man_created_at'] ? date('Y年m月d日 H:i:s', strtotime($this->cominfo['man_created_at'])) : '';

            $data['man_zhuan_info'] = (new UserService())->get_users_part_arr($this->cominfo['man_zhuan'], 'user');
            $data['man_zi_info'] = (new UserService())->get_users_part_arr($this->cominfo['man_zi'], 'user');
            $data['man_cheng_info'] = (new UserService())->get_users_part_arr($this->cominfo['man_cheng'], 'user');
            $data['man_zhian_info'] = (new UserService())->get_users_part_arr($this->cominfo['man_zhian'], 'user');

            $data['man_zhuan_lian_info'] = (new UserService())->get_users_part_arr($this->cominfo['man_zhuan_lian'], 'user');
            $data['man_zi_lian_info'] = (new UserService())->get_users_part_arr($this->cominfo['man_zi_lian'], 'user');
            $data['man_cheng_lian_info'] = (new UserService())->get_users_part_arr($this->cominfo['man_cheng_lian'], 'user');
            $data['man_zhian_lian_info'] = (new UserService())->get_users_part_arr($this->cominfo['man_zhian_lian'], 'user');
            return outputJson(2000,lang('code_2000'),$data);
        }
    }

    public function list_dept(Request $request){
        $param = $request->post();
        $where[] = ['d.deleted_user','=','0'];
        $where[] = ['d.comid','=',$this->userinfo['comid']];

        $isSea = false;

        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['d.name','like', '%'.$param['name'].'%'];
            $isSea = true;
        }
        if(isset($param['fuer']) && !empty($param['fuer'])){
            $where[] = ['u.realname','like', '%'.$param['fuer'].'%'];
            $isSea = true;
        }
        if(isset($param['type']) && !empty($param['type'])){
            $where[] = ['d.type','=', $param['type']];
            $isSea = true;
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['d.status','=', $param['status']];
            $isSea = true;
        }


        if($isSea){
            $data['data'] = DeptModel::alias('d')
                ->field('d.*,u.realname as fuer_name')
                ->leftjoin('user u','u.id=d.fuer')
                ->where($where)
                ->order('d.id DESC')->select()->toArray();
        }else{
            $data['data'] = (new UserService())->get_deptinfo_all();
        }





        $data['butauth'] = (new MenuService())->get_butauth('dept');
        return outputJson(2000,lang('code_2000'),$data);
    }

    public function add_dept(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['name'])){
                return outputJson(4000, "请输入部门名称");
            }
            if((new UserService())->check_dept_name($param['name'])){
                return outputJson(4000, "部门名称已存在");
            }
            if(empty($param['pid'])){
                return outputJson(4000, "请选择上级部门");
            }

            if($param['type'] == 2){
                $parentType = DeptModel::where(['id'=>$param['pid']])->value('type');
                if($parentType != 2){
                    return outputJson(4000, "单位的上级部门必须也为单位，请返回修改。");
                }
            }

            if($param['type'] == 2 && $this->cominfo['comnum'] > 0){
                $haveCom = DeptModel::where(['comid'=>$this->userinfo['comid'],'type'=>2,'deleted_user'=>0])
                    ->where('pid','gt',0)->count();
                if($haveCom >= $this->cominfo['comnum']){
                    return outputJson(4000, "单位数量已达上限，请联系管理员。");
                }
            }



            unset($param['token']);
            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            Db::startTrans();
            try {
                $deptid = DeptModel::insertGetId($param);
                DeptModel::where(['id'=>$deptid])->update(['sort'=>$deptid]);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'dept', $deptid);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'user', $deptid, '部门');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data['deptArr'] = (new UserService())->get_deptinfo_all();
            return outputJson(2000,lang('code_2000'),$data);
        }
    }

    public function edit_dept(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, "请输入部门名称");
            }
            if((new UserService())->check_dept_name($param['name'], $param['id'])){
                return outputJson(4000, "部门名称已存在");
            }
            if(empty($param['pid'])){
                return outputJson(4000, "请选择上级部门");
            }

            if($param['pid'] == $param['id']){
                return outputJson(4000, "上级部门不能选择当前部门");
            }

            if($param['type'] == 2){
                $parentType = DeptModel::where(['id'=>$param['pid']])->value('type');
                if($parentType != 2){
                    return outputJson(4000, "单位的上级部门必须也为单位，请返回修改。");
                }
            }

            if($param['type'] == 2 && $this->cominfo['comnum'] > 0){
                $haveCom = DeptModel::where(['comid'=>$this->userinfo['comid'],'type'=>2,'deleted_user'=>0])
                    ->where('pid','gt',0)->count();
                if($haveCom > $this->cominfo['comnum']){
                    return outputJson(4000, "单位数量已达上限，请联系管理员。");
                }
            }

            $oldPid = DeptModel::where(['id'=>$param['id']])->value('pid');
            if($oldPid < 1){
                $param['status'] = 1;
            }

            unset($param['token']);
            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            Db::startTrans();
            try {
                DeptModel::update($param);
                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'dept', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'dept', $param['id'], '部门');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = DeptModel::where(['id'=>$id])->find();
            $data['data']['fuer_info'] = (new UserService())->get_users_part_arr($data['data']['fuer'], 'user');
            $data['deptArr'] = (new UserService())->get_deptinfo_all();
            return outputJson(2000,lang('code_2000'),$data);
        }
    }

    public function addson_dept(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, "请输入部门名称");
            }
            if((new UserService())->check_dept_name($param['name'])){
                return outputJson(4000, "部门名称已存在");
            }

            if($param['type'] == 2){
                $parentType = DeptModel::where(['id'=>$param['pid']])->value('type');
                if($parentType != 2){
                    return outputJson(4000, "单位的上级部门必须也为单位，请返回修改。");
                }
            }

            if($param['type'] == 2 && $this->cominfo['comnum'] > 0){
                $haveCom = DeptModel::where(['comid'=>$this->userinfo['comid'],'type'=>2,'deleted_user'=>0])
                    ->where('pid','gt',0)->count();
                if($haveCom >= $this->cominfo['comnum']){
                    return outputJson(4000, "单位数量已达上限，请联系管理员。");
                }
            }



            unset($param['token']);
            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            Db::startTrans();
            try {
                $deptid = DeptModel::insertGetId($param);
                DeptModel::where(['id'=>$deptid])->update(['sort'=>$deptid]);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'dept', $deptid);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'dept', $deptid, '部门');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $pid = $request->get('pid',0,'int');
            $data['pid'] = $pid;
            $data['pid_name'] = DeptModel::where(['id'=>$pid])->value('name');
            return outputJson(2000,lang('code_2000'),$data);
        }
    }

    public function move_dept(Request $request){
        if($request->isPost()){
            $id = $request->post('id', 0, 'int');
            $type = $request->post('type', 0, 'int');

            $data = DeptModel::where(['id'=>$id])->find();
            if(!$data){
                return outputJson(2000,lang('code_2000'));
            }

            $list = DeptModel::where(['pid'=>$data['pid'],'deleted_user'=>0])->order('sort ASC')->column('id');
            if(count($list) < 2){
                return outputJson(2000,lang('code_2000'));
            }

            $info = [];
            if($type == 1){
                foreach ($list as $k=>$deptid){
                    if($deptid == $data['id']){
                        if($k == 0){
                            $info[] = $deptid;
                        }else{
                            $info[$k-1] = $deptid;
                            $info[$k] = $list[$k-1];
                        }
                    }else{
                        $info[] = $deptid;
                    }
                }
            }elseif($type == 2){
                foreach ($list as $k=>$deptid){
                    if($k > 0){
                        if($list[$k-1] == $data['id']){
                            $info[$k-1] = $deptid;
                            $info[$k] = $list[$k-1];
                        }else{
                            $info[] = $deptid;
                        }
                    }else{
                        $info[] = $deptid;
                    }
                }
            }else{
                $info = $list;
            }

            Db::startTrans();
            try {
                $sort = 1;
                foreach ($info as $_deptid){
                    DeptModel::where(['id'=>$_deptid])->update(['sort'=>$sort]);
                    $sort++;
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(2000,lang('code_2000'));
            }
        }
        return outputJson(2000,lang('code_2000'));
    }

    public function del_dept(Request $request){
        $param = $request->post();
        $data = DeptModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }
        if($data['pid'] == 0){
            return outputJson(4000, '默认部门不能删除');
        }

        if( DeptModel::where(['pid'=>$data['id'],'deleted_user'=>0])->find() ){
            return outputJson(4000, '该部门下子级部门，不能删除');
        }

        if( UserModel::where(['deleted_user'=>0,'deptid'=>$data['id']])->find() ){
            return outputJson(4000, '该部门下存在用户，不能删除');
        }

        Db::startTrans();
        try {
            DeptModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'dept', $data['id'], '部门');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }


    public function list_user_gang(Request $request){
        $param = $request->post();
        $where[] = ['d.deleted_user','=','0'];
        $where[] = ['d.comid','=',$this->userinfo['comid']];

        $isSea = false;

        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['d.name','like', '%'.$param['name'].'%'];
            $isSea = true;
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['d.status','=', $param['status']];
            $isSea = true;
        }


        if($isSea){
            $data['data'] = UserGangModel::alias('d')
                ->field('d.*')
                ->where($where)
                ->order('d.id DESC')->select()->toArray();
        }else{
            $data['data'] = (new UserService())->get_usergang_all();
        }

        $data['butauth'] = (new MenuService())->get_butauth('user_gang');
        return outputJson(2000,lang('code_2000'),$data);
    }

    public function add_user_gang(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['name'])){
                return outputJson(4000, "请输入岗位名称");
            }
            if((new UserService())->check_usergang_name($param['name'])){
                return outputJson(4000, "部门岗位已存在");
            }
//            if(empty($param['pid'])){
//                return outputJson(4000, "请选择上级岗位");
//            }

            unset($param['token']);
            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            Db::startTrans();
            try {
                $gangid = UserGangModel::insertGetId($param);
                UserGangModel::where(['id'=>$gangid])->update(['sort'=>$gangid]);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'user_gang', $gangid);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'user_gang', $gangid, '岗位');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data['gangArr'] = (new UserService())->get_usergang_all();
            return outputJson(2000,lang('code_2000'),$data);
        }
    }

    public function edit_user_gang(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, "请输入岗位名称");
            }
            if((new UserService())->check_usergang_name($param['name'], $param['id'])){
                return outputJson(4000, "岗位名称已存在");
            }
//            if(empty($param['pid'])){
//                return outputJson(4000, "请选择上级岗位");
//            }

            unset($param['token']);
            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            Db::startTrans();
            try {
                UserGangModel::update($param);
                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'user_gang', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'user_gang', $param['id'], '岗位');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = UserGangModel::where(['id'=>$id])->find();
            $data['gangArr'] = (new UserService())->get_usergang_all();
            return outputJson(2000,lang('code_2000'),$data);
        }
    }

    public function addson_user_gang(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['name'])){
                return outputJson(4000, "请输入岗位名称");
            }

            unset($param['token']);
            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            Db::startTrans();
            try {
                $gangid = UserGangModel::insertGetId($param);
                UserGangModel::where(['id'=>$gangid])->update(['sort'=>$gangid]);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'user_gang', $gangid);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'user_gang', $gangid, '岗位');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $pid = $request->get('pid',0,'int');
            $data['pid'] = $pid;
            $data['pid_name'] = UserGangModel::where(['id'=>$pid])->value('name');
            return outputJson(2000,lang('code_2000'),$data);
        }
    }

    public function del_user_gang(Request $request){
        $param = $request->post();
        $data = UserGangModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        if( UserGangModel::where(['pid'=>$data['id'],'deleted_user'=>0])->find() ){
            return outputJson(4000, '该岗位下存在子级岗位，不能删除');
        }

        if( UserModel::where(['deleted_user'=>0,'gangid'=>$data['id']])->find() ){
            return outputJson(4000, '该岗位下存在用户，不能删除');
        }

        Db::startTrans();
        try {
            UserGangModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'user_gang', $data['id'], '岗位');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }

    public function show_user_gang(Request $request){
        $id = $request->post('id', 0, 'int');
        $data = UserGangModel::get_info_by_pk($id);
        if(!$data){
            return outputJson(4000, lang('code_4000'));
        }
        $data['pid_name'] = UserGangModel::where(['id'=>$data['pid']])->value('name');
        $data['status_name'] = $data['status'] > 0 ? '正常' : '停用';
        $data['created_user'] = UserModel::get_realname_by_pk($data['created_user']);
        $data['updated_user'] = UserModel::get_realname_by_pk($data['updated_user']);
        $data['butauth'] = (new MenuService())->get_butauth('usergang');
        return outputJson(2000,lang('code_2000'), $data);
    }


    public function list_user(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['user.deleted_user','=', 0];
        $where[] = ['user.comid','=',$this->userinfo['comid']];

        if(isset($param['tel']) && !empty($param['tel'])){
            $where[] = ['user.tel','like', '%'.$param['tel'].'%'];
        }
        if(isset($param['realname']) && !empty($param['realname'])){
            $where[] = ['user.realname','like', '%'.$param['realname'].'%'];
        }
        if(isset($param['deptid']) && !empty($param['deptid'])){
            $where[] = ['user.deptid','=', $param['deptid']];
        }

        $whereRoleid = '';
        if(isset($param['roleid']) && $param['roleid'] != ''){
            $whereRoleid = Db::raw("FIND_IN_SET(".$param['roleid'].",`user`.`roleid`)");
        }

        $whereGangid = '';
        if(isset($param['gangid']) && $param['gangid'] != ''){
            $whereGangid = Db::raw("FIND_IN_SET(".$param['gangid'].",`user`.`gangid`)");
        }

        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['user.status','=', $param['status']];
        }

        $data['is_roleid'] = isset($param['roleid']) ? $param['roleid'] : '';

        $data['data'] = UserModel::alias('user')
            ->field('user.*')
            ->where($where)->where($whereRoleid)->where($whereGangid)
            ->order('user.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['deptid_name'] = DeptModel::get_name_by_pk($item['deptid']);
                $item['gangid_name'] = UserGangModel::get_name_by_ids($item['gangid'],' / ');
                $item['roleid_name'] = UserRoleModel::get_name_by_ids($item['roleid'],' / ');
                return $item;
            })->toArray();

        $data['gangArr'] = (new UserService())->get_usergang_all();
        $data['roleArr'] = (new UserService())->get_user_roleArr();
        $data['butauth'] = (new MenuService())->get_butauth('user');
        return outputJson(2000,lang('code_2000'),$data);
    }

    public function list_user_dept(Request $request){
        $data = (new UserService())->get_list_user_dept();
        return outputJson(2000,lang('code_2000'),$data);
    }

    public function add_user(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['realname'])){
                return outputJson(4000, '请输入姓名');
            }
            if((new UserService())->check_user_name($param['realname'])){
                return outputJson(4000, '用户姓名已存在');
            }
            if( !check_phone($param['tel']) ){
                return outputJson(4000, '请输入有效手机号码');
            }
            if( (new UserService())->check_login_tel($param['tel']) ){
                return outputJson(4000, '登录手机号码已存在');
            }
            if(empty($param['deptid'])){
                return outputJson(4000, '请选择部门');
            }
            if(empty($param['roleid'])){
                return outputJson(4000, '请选择角色');
            }

            if(empty($param['pass'])){
                $param['pass'] = $param['tel'];
            }
            $param['pass'] = md5(md5($param['pass']));
            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');

            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);

            Db::startTrans();
            try {
                $userid = UserModel::insertGetId($param);
                (new OptService())->relation_file($files,'user',$userid);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'user', $userid);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'user', $userid, '用户');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,$e->getMessage());
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data['deptArr'] = (new UserService())->get_deptinfo_all();
            $data['gangArr'] = (new UserService())->get_usergang_all();

            $roleArr = [];
            $typeArr = (new UserService())->get_user_role_type();
            foreach ($typeArr as $k=>$v){
                $arr = UserRoleModel::field('*,id as value')
                    ->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'type'=>$k])
                    ->order('sort ASC')->select()->toArray();
                if(!$arr){
                    $arr = [];
                }
                $roleArr[$k] = $arr;
            }
            $data['roleArr'] = $roleArr;
            return outputJson(2000,lang('code_2000'), $data);
        }
    }

    public function add_userreg(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['realname'])){
                return outputJson(4000, '请输入姓名');
            }
            if((new UserService())->check_user_name($param['realname'])){
                return outputJson(4000, '用户姓名已存在');
            }
            if( !check_phone($param['tel']) ){
                return outputJson(4000, '请输入有效手机号码');
            }
            if( (new UserService())->check_login_tel($param['tel']) ){
                return outputJson(4000, '登录手机号码已存在');
            }


            if(empty($param['pass'])){
                $param['pass'] = $param['tel'];
            }

            $param['reg_pass'] = $param['pass'];
            $param['pass'] = md5(md5($param['pass']));
            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');



            if($param['reg_vision'] == 'wisecert'){
                $param['comid'] = 1;
                $param['deptid'] = 2;
                $param['gangid'] = 6;
                $param['roleid'] = 25;
            }else{
                $param['comid'] = 1;
                $param['deptid'] = 34;
                $param['gangid'] = 1;
                $param['roleid'] = 24;
            }

            $param['reg_name'] = $param['realname'];
            $param['isreg'] = 1;
            $param['reg_tel'] = $param['tel'];
            $param['reg_ip'] = $request->ip();
            $param['reg_enddt'] = date("Y-m-d H:i:s", time()+15*24*3600);

            unset($param['token']);

            Db::startTrans();
            try {
                $userid = UserModel::insertGetId($param);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'user', $userid);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'user', $userid, '用户');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{

            return outputJson(2000,lang('code_2000'), []);
        }
    }

    public function edit_user(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['realname'])){
                return outputJson(4000, '请输入姓名');
            }
            if((new UserService())->check_user_name($param['realname'], $param['id'])){
                return outputJson(4000, '用户姓名已存在');
            }
            if( !check_phone($param['tel']) ){
                return outputJson(4000, '请输入有效手机号码');
            }
            if( (new UserService())->check_login_tel($param['tel'], $param['id']) ){
                return outputJson(4000, '登录手机号码已存在');
            }
            if(empty($param['deptid'])){
                return outputJson(4000, '请选择部门');
            }
            if(empty($param['roleid'])){
                return outputJson(4000, '请选择角色');
            }

            if(empty($param['pass'])){
                unset($param['pass']);
            }else{
                $param['pass'] = md5(md5($param['pass']));
            }

            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);

            Db::startTrans();
            try {
                UserModel::update($param);
                (new OptService())->relation_file($files,'user',$param['id']);
                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'user', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'user', $param['id'], '用户');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = UserModel::where(['id'=>$id])->find();
            $data['data']['gangid'] = explode(',', $data['data']['gangid']);
            $data['data']['roleid'] = explode(',', $data['data']['roleid']);
            $data['deptArr'] = (new UserService())->get_deptinfo_all();
            $data['gangArr'] = (new UserService())->get_usergang_all();

            $data['data']['lianer_info'] = DealcomModel::where('id','in',$data['data']['lianer'])->select()->toArray();
            $data['data']['gonger_info'] = DealcomModel::where('id','in',$data['data']['gonger'])->select()->toArray();

            $data['data']['roleidArr'] = UserRoleModel::where('id','in',$data['data']['roleid'])->group('type')->column('type');


            $roleArr = [];
            $typeArr = (new UserService())->get_user_role_type();
            foreach ($typeArr as $k=>$v){
                $arr = UserRoleModel::field('*,id as value')
                    ->where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'type'=>$k])
                    ->order('sort ASC')->select()->toArray();
                if(!$arr){
                    $arr = [];
                }
                $roleArr[$k] = $arr;
            }
            $data['roleArr'] = $roleArr;

            $data['files'] = (new OptService())->get_file('user', $data['data']['id']);
            return outputJson(2000,lang('code_2000'),$data);
        }
    }

    public function edit_userreg(Request $request){
        if($request->isPost()){
            $param = $request->post();


            unset($param['token']);

            Db::startTrans();
            try {
                UserModel::update($param);

                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'user', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'user', $param['id'], '用户');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = UserModel::where(['id'=>$id])->find();
            return outputJson(2000,lang('code_2000'),$data);
        }
    }

    public function setpass_user(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['pass'])){
                return outputJson(4000, '请输入新密码');
            }
            if(empty($param['passcon'])){
                return outputJson(4000, '请输入确认密码');
            }
            if($param['pass'] != $param['passcon']){
                return outputJson(4000, '新密码与确认密码输入不一致');
            }

            $param['pass'] = md5(md5($param['pass']));
            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            unset($param['token']);

            Db::startTrans();
            try {
                UserModel::where(['id'=>$param['id']])->update(['pass'=>$param['pass']]);
                (new OptService())->add_flow_log('重置密码', 'user', $param['id']);
                (new OptService())->add_log_list('重置密码', 'user', $param['id'], '用户');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = UserModel::where(['id'=>$id])->find();
            return outputJson(2000,lang('code_2000'),$data);
        }
    }
    public function updpass_user(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['oldpass'])){
                return outputJson(4000, '请输入旧密码');
            }
            if(empty($param['pass'])){
                return outputJson(4000, '请输入新密码');
            }
            if(empty($param['passcon'])){
                return outputJson(4000, '请输入确认密码');
            }
            if($param['pass'] != $param['passcon']){
                return outputJson(4000, '新密码与确认密码输入不一致');
            }

            if(md5(md5($param['oldpass'])) != $this->userinfo['pass']){
                return outputJson(4000, '旧密码错误');
            }


            $param['pass'] = md5(md5($param['pass']));

            Db::startTrans();
            try {
                UserModel::where(['id'=>$this->userinfo['id']])->update(['pass'=>$param['pass']]);
                (new OptService())->add_flow_log('修改密码', 'user', $param['id']);
                (new OptService())->add_log_list('修改密码', 'user', $param['id'], '用户');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,$e->getMessage());
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }
    }

    public function signrole_user(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            unset($param['token']);

            Db::startTrans();
            try {
                UserModel::where(['id'=>$param['id']])->update(['roleid'=>$param['roleid']]);
                (new OptService())->add_flow_log('分配角色', 'user', $param['id']);
                (new OptService())->add_log_list('分配角色', 'user', $param['id'], '用户');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = UserModel::where(['id'=>$id])->find();
            $data['data']['roleid'] = explode(',', $data['data']['roleid']);
            $data['roleArr'] = (new UserService())->get_user_roleArr();
            return outputJson(2000,lang('code_2000'),$data);
        }
    }

    public function del_user(Request $request){
        $param = $request->post();
        $data = UserModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }
        if($data['issuper'] > 0){
            return outputJson(4000, '超管不能删除');
        }

        Db::startTrans();
        try {
            UserModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'user', $data['id'], '用户');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }

    public function show_user(Request $request){
        $id = $request->post('id', 0, 'int');
        $data = UserModel::get_info_by_pk($id);
        if(!$data){
            return outputJson(4000, lang('code_4000'));
        }
        $data['status_name'] = $data['status'] > 0 ? '正常' : '停用';
        $data['deptid_name'] = DeptModel::get_name_by_pk($data['deptid']);
        $data['gangid_name'] = UserGangModel::get_name_by_ids($data['gangid'], '，');
        $data['roleid_name'] = UserRoleModel::get_name_by_ids($data['roleid'], '，');
        $data['files'] = (new OptService())->get_file('user', $data['id']);
        return outputJson(2000,lang('code_2000'), $data);
    }

    public function show_userinfo(Request $request){
        $data = UserModel::get_info_by_pk($this->userinfo['id']);
        if(!$data){
            return outputJson(4000, lang('code_4000'));
        }
        $data['status_name'] = $data['status'] > 0 ? '正常' : '停用';
        $data['deptid_name'] = DeptModel::get_name_by_pk($data['deptid']);
        $data['gangid_name'] = UserGangModel::get_name_by_ids($data['gangid'], '，');
        $data['roleid_name'] = UserRoleModel::get_name_by_ids($data['roleid'], '，');

        $wx_bind_img = $this->userinfo['wx_bindimg'];

        if(!$wx_bind_img){
            $wx_bind_img = (new Wechat())->create_qrcode($this->userinfo['id']);
            UserModel::where(['id'=>$this->userinfo['id']])->update(['wx_bindimg'=>$wx_bind_img]);
        }

        $data['wx'] = [
            'wx_bindimg' => $wx_bind_img,
            'wx_openid' => $this->userinfo['wx_openid'],
            'wx_nickname' => $this->userinfo['wx_nickname'],
            'wx_headimgurl' => $this->userinfo['wx_headimgurl'],
            'wx_bangdt' => $this->userinfo['wx_bangdt'],
        ];
        return outputJson(2000,lang('code_2000'), $data);
    }

    public function wxno_userinfo(Request $request){
        if($request->isPost()){
            UserModel::where(['id'=>$this->userinfo['id']])->update([
                'wx_openid' => '',
                'wx_nickname' => '',
                'wx_headimgurl' => '',
                'wx_bangdt' => '',
            ]);
        }
        return outputJson(2000,lang('code_2000'));
    }


    public function list_user_role(Request $request){
        $param = $request->post();

        $where[] = ['deleted_user','=', 0];
        $where[] = ['comid','=',$this->userinfo['comid']];

        if(isset($param['type']) && !empty($param['type'])){
            $where[] = ['type','=', $param['type']];
        }else{
            $where[] = ['type','=', 1];
        }
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['name','like', '%'.$param['name'].'%'];
        }

        $data['data'] = UserRoleModel::where($where)
            ->order('sort ASC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['type_name'] = (new UserService())->get_user_role_type_name($item['type']);
                $item['users'] = UserModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0])
                    ->where( Db::raw("FIND_IN_SET(".$item['id'].",`roleid`)") )->count();
                return $item;
            })->toArray();


        if(isset($param['type'])){
            if($param['type'] == 1){
                $data['butauth'] = (new MenuService())->get_butauth('user_role');
            }
            if($param['type'] == 2){
                $data['butauth'] = (new MenuService())->get_butauth('user_role_engin');
            }
            if($param['type'] == 3){
                $data['butauth'] = (new MenuService())->get_butauth('user_role_lian');
            }
            if($param['type'] == 4){
                $data['butauth'] = (new MenuService())->get_butauth('user_role_gong');
            }
            if($param['type'] == 5){
                $data['butauth'] = (new MenuService())->get_butauth('user_role_fen');
            }
        }else{
            $data['butauth'] = (new MenuService())->get_butauth('user_role');
        }


        return outputJson(2000,lang('code_2000'),$data);
    }

    public function add_user_role(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['name'])){
                return outputJson(4000, '请输入名称');
            }
            if((new UserService())->check_userrole_name($param['name'])){
                return outputJson(4000, '名称已存在');
            }

            $authArr = [];
            if(isset($param['auth'])){
                foreach ($param['auth'] as $k=>$v){
                    foreach ($v as $kk=>$vv){
                        $authArr[$kk] = $vv;
                    }
                }
                $param['auth'] = json_encode($authArr);
            }else{
                $param['auth'] = '';
            }

            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            unset($param['token']);

            Db::startTrans();
            try {
                $roleid = UserRoleModel::insertGetId($param);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'user_role', $roleid);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'user_role', $roleid, '角色');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $type = $request->get('type', 1 ,'int');

            $whereMenus = [];
            $whereButs = [];
            if($type != 1){
                $menus = (new UserService())->get_user_role_type_menus();
                $typeMenes = isset($menus[$type]) ? $menus[$type] : [];
                $whereMenus[] = ['id','in',$typeMenes];

                $buts = (new UserService())->get_user_role_type_buts();
                $typeButs = isset($buts[$type]) ? $buts[$type] : [];
                $whereButs[] = ['id','in',$typeButs];
            }


            $menu = MenuModel::field('*,id as value')->where(['pid'=>0,'status'=>1])->where('id','neq',1)->where($whereMenus)->order('sort ASC')->select()->toArray();
            foreach ($menu as &$item){
                $item['children'] = MenuModel::field('*,id as value')->where(['pid'=>$item['id'],'status'=>1])->where($whereMenus)->order('sort ASC')->select()->toArray();
                $item['but'] = [];
                foreach ($item['children'] as &$item22){
                    $item22['children'] = MenuModel::field('*,id as value')->where(['pid'=>$item22['id'],'status'=>1])->where($whereMenus)->order('sort ASC')->select()->toArray();
                    if($item22['modedir']){
                        $item22['but'] = MenuButModel::where(['modedir'=>$item22['modedir'],'status'=>1])->where($whereButs)->order('sort ASC')->select()->toArray();
                    }else{
                        $item22['but'] = [];
                    }
                    foreach ($item22['children'] as &$item33){
                        if($item33['modedir']){
                            $item33['but'] = MenuButModel::where(['modedir'=>$item33['modedir'],'status'=>1])->where($whereButs)->order('sort ASC')->select()->toArray();
                        }else{
                            $item33['but'] = [];
                        }
                    }
                }
            }

//            $data['dataAuth'] = (new UserService())->get_role_data_auth();
            $data['data'] = $menu;
            return outputJson(2000,lang('code_2000'), $data);
        }
    }

    public function edit_user_role(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['name'])){
                return outputJson(4000, '请输入名称');
            }
            if((new UserService())->check_userrole_name($param['name'], $param['id'])){
                return outputJson(4000, '名称已存在');
            }

            $authArr = [];
            if(isset($param['auth'])){
                foreach ($param['auth'] as $k=>$v){
                    foreach ($v as $kk=>$vv){
                        $authArr[$kk] = $vv;
                    }
                }
                $param['auth'] = json_encode($authArr);
            }else{
                $param['auth'] = '';
            }

            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at'] = date('Y-m-d H:i:s');
            unset($param['token']);

            Db::startTrans();
            try {
                UserRoleModel::update($param);
                (new OptService())->add_flow_log(FlowLogModel::SET_EDIT, 'user_role', $param['id']);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'user_role', $param['id'], '角色');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $role = UserRoleModel::where(['id'=>$id])->find();
            if(!$role){
                return outputJson(2000,lang('code_2000'),[]);
            }

            $role['updated_user'] = UserModel::get_realname_by_pk($role['updated_user']);

            $existMenu = explode(',', $role['menu']);
            $existBut = explode(',', $role['but']);
            $existAuth = json_decode($role['auth'],true);



            $whereMenus = [];
            $whereButs = [];
            if($role['type'] != 1){
                $menus = (new UserService())->get_user_role_type_menus();
                $typeMenes = isset($menus[$role['type']]) ? $menus[$role['type']] : [];
                $whereMenus[] = ['id','in',$typeMenes];

                $buts = (new UserService())->get_user_role_type_buts();
                $typeButs = isset($buts[$role['type']]) ? $buts[$role['type']] : [];
                $whereButs[] = ['id','in',$typeButs];
            }


            $menu = MenuModel::field('*,id as value')->where(['pid'=>0,'status'=>1])->where('id','neq',1)->where($whereMenus)->order('sort ASC')->select()->toArray();
            foreach ($menu as &$item){
                $item['checked'] = false;
                if(in_array($item['id'], $existMenu)){
                    $item['checked'] = true;
                }
                $item['children'] = MenuModel::field('*,id as value')->where(['pid'=>$item['id'],'status'=>1])->where($whereMenus)->order('sort ASC')->select()->toArray();
                $item['but'] = [];
                foreach ($item['children'] as &$item22){
                    $item22['checked'] = false;
                    if(in_array($item22['id'], $existMenu)){
                        $item22['checked'] = true;
                    }

                    $item22['children'] = MenuModel::field('*,id as value')->where(['pid'=>$item22['id'],'status'=>1])->where($whereMenus)->order('sort ASC')->select()->toArray();
                    if($item22['modedir']){
                        if(isset($existAuth[$item22['id']])){
                            $item22['auth'] = $existAuth[$item22['id']];
                        }
                        $item22['but'] = MenuButModel::where(['modedir'=>$item22['modedir'],'status'=>1])->where($whereButs)->order('sort ASC')->select()->toArray();
                        foreach ($item22['but'] as $but_k=>&$but_v){
                            $but_v['checked'] = false;
                            if(in_array($but_v['id'], $existBut)){
                                $but_v['checked'] = true;
                            }
                        }
                    }else{
                        $item22['but'] = [];
                    }
                    foreach ($item22['children'] as &$item33){
                        $item33['checked'] = false;
                        if(in_array($item33['id'], $existMenu)){
                            $item33['checked'] = true;
                        }
                        if($item33['modedir']){
                            if(isset($existAuth[$item33['id']])){
                                $item33['auth'] = $existAuth[$item33['id']];
                            }
                            $item33['but'] = MenuButModel::where(['modedir'=>$item33['modedir'],'status'=>1])->where($whereButs)->order('sort ASC')->select()->toArray();
                            foreach ($item33['but'] as $but_k=>&$but_v){
                                $but_v['checked'] = false;
                                if(in_array($but_v['id'], $existBut)){
                                    $but_v['checked'] = true;
                                }
                            }
                        }else{
                            $item33['but'] = [];
                        }
                    }
                }
            }

            $data['role'] = $role;
//            $data['dataAuth'] = (new UserService())->get_role_data_auth();
            $data['data'] = $menu;
            return outputJson(2000,lang('code_2000'),$data);
        }
    }

    public function copyauth_user_role(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['name'])){
                return outputJson(4000, '请输入名称');
            }
            if((new UserService())->check_userrole_name($param['name'])){
                return outputJson(4000, '名称已存在');
            }

            $authArr = [];
            if(isset($param['auth'])){
                foreach ($param['auth'] as $k=>$v){
                    foreach ($v as $kk=>$vv){
                        $authArr[$kk] = $vv;
                    }
                }
                $param['auth'] = json_encode($authArr);
            }else{
                $param['auth'] = '';
            }

            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            unset($param['token']);

            Db::startTrans();
            try {
                $roleid = UserRoleModel::insertGetId($param);
                (new OptService())->add_flow_log('复制权限', 'user_role', $roleid);
                (new OptService())->add_log_list('复制权限', 'user_role', $roleid, '角色');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $role = UserRoleModel::where(['id'=>$id])->find();
            if(!$role){
                return outputJson(2000,lang('code_2000'),[]);
            }

            $role['updated_user'] = UserModel::get_realname_by_pk($role['updated_user']);

            $existMenu = explode(',', $role['menu']);
            $existBut = explode(',', $role['but']);
            $existAuth = json_decode($role['auth'],true);

            $whereMenus = [];
            $whereButs = [];

            if($role['type'] != 1){
                $menus = (new UserService())->get_user_role_type_menus();
                $typeMenes = isset($menus[$role['type']]) ? $menus[$role['type']] : [];
                $whereMenus[] = ['id','in',$typeMenes];

                $buts = (new UserService())->get_user_role_type_buts();
                $typeButs = isset($buts[$role['type']]) ? $buts[$role['type']] : [];
                $whereButs[] = ['id','in',$typeButs];
            }


            $menu = MenuModel::field('*,id as value')->where(['pid'=>0,'status'=>1])->where('id','neq',1)->where($whereMenus)->order('sort ASC')->select()->toArray();
            foreach ($menu as &$item){
                $item['checked'] = false;
                if(in_array($item['id'], $existMenu)){
                    $item['checked'] = true;
                }
                $item['children'] = MenuModel::field('*,id as value')->where(['pid'=>$item['id'],'status'=>1])->where($whereMenus)->order('sort ASC')->select()->toArray();
                $item['but'] = [];
                foreach ($item['children'] as &$item22){
                    $item22['checked'] = false;
                    if(in_array($item22['id'], $existMenu)){
                        $item22['checked'] = true;
                    }

                    $item22['children'] = MenuModel::field('*,id as value')->where(['pid'=>$item22['id'],'status'=>1])->where($whereMenus)->order('sort ASC')->select()->toArray();
                    if($item22['modedir']){
                        if(isset($existAuth[$item22['id']])){
                            $item22['auth'] = $existAuth[$item22['id']];
                        }
                        $item22['but'] = MenuButModel::where(['modedir'=>$item22['modedir'],'status'=>1])->where($whereButs)->order('sort ASC')->select()->toArray();
                        foreach ($item22['but'] as $but_k=>&$but_v){
                            $but_v['checked'] = false;
                            if(in_array($but_v['id'], $existBut)){
                                $but_v['checked'] = true;
                            }
                        }
                    }else{
                        $item22['but'] = [];
                    }
                    foreach ($item22['children'] as &$item33){
                        $item33['checked'] = false;
                        if(in_array($item33['id'], $existMenu)){
                            $item33['checked'] = true;
                        }
                        if($item33['modedir']){
                            if(isset($existAuth[$item33['id']])){
                                $item33['auth'] = $existAuth[$item33['id']];
                            }
                            $item33['but'] = MenuButModel::where(['modedir'=>$item33['modedir'],'status'=>1])->where($whereButs)->order('sort ASC')->select()->toArray();
                            foreach ($item33['but'] as $but_k=>&$but_v){
                                $but_v['checked'] = false;
                                if(in_array($but_v['id'], $existBut)){
                                    $but_v['checked'] = true;
                                }
                            }
                        }else{
                            $item33['but'] = [];
                        }
                    }
                }
            }

            $data['role'] = $role;
//            $data['dataAuth'] = (new UserService())->get_role_data_auth();
            $data['data'] = $menu;
            return outputJson(2000,lang('code_2000'),$data);
        }
    }

    public function move_user_role(Request $request){
        if($request->isPost()){
            $id = $request->post('id', 0, 'int');
            $type = $request->post('type', 0, 'int');

            $data = UserRoleModel::where(['id'=>$id])->find();
            if(!$data){
                return outputJson(2000,lang('code_2000'));
            }

            $list = UserRoleModel::where(['deleted_user'=>0])->order('sort ASC')->column('id');
            if(count($list) < 2){
                return outputJson(2000,lang('code_2000'));
            }

            $info = [];
            if($type == 1){
                foreach ($list as $k=>$opid){
                    if($opid == $data['id']){
                        if($k == 0){
                            $info[] = $opid;
                        }else{
                            $info[$k-1] = $opid;
                            $info[$k] = $list[$k-1];
                        }
                    }else{
                        $info[] = $opid;
                    }
                }
            }elseif($type == 2){
                foreach ($list as $k=>$opid){
                    if($k > 0){
                        if($list[$k-1] == $data['id']){
                            $info[$k-1] = $opid;
                            $info[$k] = $list[$k-1];
                        }else{
                            $info[] = $opid;
                        }
                    }else{
                        $info[] = $opid;
                    }
                }
            }else{
                $info = $list;
            }

            Db::startTrans();
            try {
                $sort = 1;
                foreach ($info as $_opid){
                    UserRoleModel::where(['id'=>$_opid])->update(['sort'=>$sort]);
                    $sort++;
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(2000,lang('code_2000'));
            }
        }
        return outputJson(2000,lang('code_2000'));
    }

    public function del_user_role(Request $request){
        $param = $request->post();
        $data = UserRoleModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        $exist = UserModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0])
            ->where( Db::raw("FIND_IN_SET(".$data['id'].",`roleid`)") )
            ->find();
        if($exist){
            return outputJson(4000, '该角色下存在用户，暂不能删除');
        }

        Db::startTrans();
        try {
            UserRoleModel::where(['id'=>$data['id']])->delete();
            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'user_role', $data['id'], '角色');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }

    public function show_user_role(Request $request){
        $id = $request->post('id', 0, 'int');
        $data = UserRoleModel::get_info_by_pk($id);
        if(!$data){
            return outputJson(4000, lang('code_4000'));
        }


        $data['type_name'] = (new UserService())->get_user_role_type_name($data['type']);

        $data['userarr'] = UserModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0])
            ->where( Db::raw("FIND_IN_SET(".$data['id'].",`roleid`)") )->select()->toArray();
        $data['users'] = count($data['userarr']);

        $data['updated_user'] = UserModel::get_realname_by_pk($data['updated_user']);

        $existMenu = explode(',', $data['menu']);
        $existBut = explode(',', $data['but']);
        $existAuth = json_decode($data['auth'],true);


        $whereMenus = [];
        $whereMenus[] = ['status','=',1];
        $whereButs = [];
        if($data['type'] != 1){
            $menus = (new UserService())->get_user_role_type_menus();
            $typeMenes = isset($menus[$data['type']]) ? $menus[$data['type']] : [];
            $whereMenus[] = ['id','in',$typeMenes];

            $buts = (new UserService())->get_user_role_type_buts();
            $typeButs = isset($buts[$data['type']]) ? $buts[$data['type']] : [];
            $whereButs[] = ['id','in',$typeButs];
        }

        $menu = MenuModel::field('*,id as value')->where(['pid'=>0])->where($whereMenus)->order('sort ASC')->select()->toArray();
        foreach ($menu as &$item){
            $item['checked'] = false;
            if(in_array($item['id'], $existMenu)){
                $item['checked'] = true;
            }
            $item['children'] = MenuModel::field('*,id as value')->where(['pid'=>$item['id']])->where($whereMenus)->order('sort ASC')->select()->toArray();
            $item['but'] = [];
            foreach ($item['children'] as &$item22){
                $item22['checked'] = false;
                if(in_array($item22['id'], $existMenu)){
                    $item22['checked'] = true;
                }

                $item22['children'] = MenuModel::field('*,id as value')->where(['pid'=>$item22['id']])->where($whereMenus)->order('sort ASC')->select()->toArray();
                if($item22['modedir']){
                    if(isset($existAuth[$item22['id']])){
                        $item22['auth'] = $existAuth[$item22['id']];
                    }
                    $item22['but'] = MenuButModel::where(['modedir'=>$item22['modedir'],'status'=>1])->where($whereButs)->order('sort ASC')->select()->toArray();
                    foreach ($item22['but'] as $but_k=>&$but_v){
                        $but_v['checked'] = false;
                        if(in_array($but_v['id'], $existBut)){
                            $but_v['checked'] = true;
                        }
                    }
                }else{
                    $item22['but'] = [];
                }
                foreach ($item22['children'] as &$item33){
                    $item33['checked'] = false;
                    if(in_array($item33['id'], $existMenu)){
                        $item33['checked'] = true;
                    }
                    if($item33['modedir']){
                        if(isset($existAuth[$item33['id']])){
                            $item33['auth'] = $existAuth[$item33['id']];
                        }
                        $item33['but'] = MenuButModel::where(['modedir'=>$item33['modedir'],'status'=>1])->where($whereButs)->order('sort ASC')->select()->toArray();
                        foreach ($item33['but'] as $but_k=>&$but_v){
                            $but_v['checked'] = false;
                            if(in_array($but_v['id'], $existBut)){
                                $but_v['checked'] = true;
                            }
                        }
                    }else{
                        $item33['but'] = [];
                    }
                }
            }
        }

//        $data['dataAuth'] = (new UserService())->get_role_data_auth();
        $data['data'] = $menu;
        return outputJson(2000,lang('code_2000'), $data);
    }


    public function list_loginlist(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['comid','=',$this->userinfo['comid']];

        if(isset($param['realname']) && !empty($param['realname'])){
            $where[] = ['realname','like', '%'.$param['realname'].'%'];
        }
        if(isset($param['tel']) && !empty($param['tel'])){
            $where[] = ['tel','like', '%'.$param['tel'].'%'];
        }
        if(isset($param['dept']) && !empty($param['dept'])){
            $where[] = ['dept','like', '%'.$param['dept'].'%'];
        }
        if(isset($param['role']) && !empty($param['role'])){
            $where[] = ['role','like', '%'.$param['role'].'%'];
        }
        if(isset($param['ip']) && !empty($param['ip'])){
            $where[] = ['ip','like', '%'.$param['ip'].'%'];
        }
        if(isset($param['type']) && !empty($param['type'])){
            $where[] = ['type','=', $param['type']];
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['status','=', $param['status']];
        }
        if(isset($param['optdt']) && !empty($param['optdt'])){
            $opt = explode(' - ', $param['optdt']);
            $where[] = ['optdt','between', [$opt[0].' 00:00:00', $opt[1].' 23:59:59']];
        }

        $data['data'] = LoginListModel::where($where)
            ->order('id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['type_name'] = $item['type'] == 1 ? 'PC端' : '手机端';
                return $item;
            })->toArray();
        return outputJson(2000,lang('code_2000'),$data);
    }

    public function list_loglist(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['list.comid','=',$this->userinfo['comid']];

        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['list.name','like', '%'.$param['name'].'%'];
        }
        if(isset($param['butname']) && !empty($param['butname'])){
            $where[] = ['list.butname','like', '%'.$param['butname'].'%'];
        }
        if(isset($param['ip']) && !empty($param['ip'])){
            $where[] = ['list.ip','like', '%'.$param['ip'].'%'];
        }
        if(isset($param['realname']) && !empty($param['realname'])){
            $where[] = ['list.realname','like', '%'.$param['realname'].'%'];
        }
        if(isset($param['deptname']) && !empty($param['deptname'])){
            $where[] = ['list.deptname','like', '%'.$param['deptname'].'%'];
        }
        if(isset($param['optdt']) && !empty($param['optdt'])){
            $opt = explode(' - ', $param['optdt']);
            $where[] = ['optdt','between', [$opt[0].' 00:00:00', $opt[1].' 23:59:59']];
        }

        $data['data'] = LogListModel::alias('list')
            ->field('list.*')
            ->where($where)
            ->order('list.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['isshow'] = false;

                try {
                    $exist = Db::name($item['table'])->where(['id'=>$item['mid']])->find();
                    if($exist){
                        if(!isset($exist['deleted_user']) || ( isset($exist['deleted_user']) && $exist['deleted_user']==0 )){
                            $item['isshow'] = true;
                        }
                    }
                } catch (\Exception $e) {

                }
                return $item;
            })->toArray();
        return outputJson(2000,lang('code_2000'),$data);
    }

    public function list_logreg(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['list.comid','=',1];
        $where[] = ['list.deleted_user','=',0];
        $where[] = ['list.isreg','=',1];

        if(isset($param['reg_name']) && !empty($param['reg_name'])){
            $where[] = ['list.reg_name','like', '%'.$param['reg_name'].'%'];
        }
        if(isset($param['reg_tel']) && !empty($param['reg_tel'])){
            $where[] = ['list.reg_tel','like', '%'.$param['reg_tel'].'%'];
        }
        if(isset($param['reg_com']) && !empty($param['reg_com'])){
            $where[] = ['list.reg_com','like', '%'.$param['reg_com'].'%'];
        }
        if(isset($param['reg_vision']) && !empty($param['reg_vision'])){
            $where[] = ['list.reg_vision','like', '%'.$param['reg_vision'].'%'];
        }

        $data['data'] = UserModel::alias('list')
            ->field('list.*')
            ->where($where)
            ->order('list.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['loginnum'] = LoginTokenModel::where(['comid'=>$item['comid'],'uid'=>$item['id']])->count();
                $item['loginlastdt'] = LoginTokenModel::where(['comid'=>$item['comid'],'uid'=>$item['id']])->order('id DESC')->value('optdt');
                return $item;
            })->toArray();
        return outputJson(2000,lang('code_2000'),$data);
    }


    public function list_option(Request $request){
        $opid = $request->post('opid', 0, 'int');

        if($opid){
            $data['data'] = (new UserService())->get_optioninfo_all($opid);
        }else{
            $data['data'] = [];
        }

        $data['butauth'] = (new MenuService())->get_butauth('option');
        return outputJson(2000,lang('code_2000'),$data);
    }

    public function list_option_nav(Request $request){
        $data = [];
        $nav = (new UserService())->get_option_nav();
        foreach ($nav as $k=>$v){
            $item['title'] = $v;
            $item['spread'] = true;
            $item['children'] = OptionModel::field('id,name as title')->where(['pid'=>0,'modname'=>$k])->order('sort ASC')->select()->toArray();
            $data[] = $item;
        }
        return outputJson(2000,lang('code_2000'),$data);
    }

    public function add_option(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['name'])){
                return outputJson(4000, '请输入名称');
            }
            if((new UserService())->check_option_name($param['name'], $param['opid'])){
                return outputJson(4000, '名称已存在');
            }
            if(empty($param['keyid'])){
                return outputJson(4000, '请输入键值');
            }
            if((new UserService())->check_option_keyid($param['keyid'], $param['opid'])){
                return outputJson(4000, '键值已存在');
            }


            if(empty($param['pid'])){
                $param['pid'] = $param['opid'];
            }

            $param['topid'] = $param['opid'];
            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            unset($param['token']);
            unset($param['opid']);

            Db::startTrans();
            try {
                $optionid = OptionModel::insertGetId($param);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'option', $optionid, '基础数据');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $opid = $request->get('opid',0,'int');
            if($opid){
                $data['pidArr'] = (new UserService())->get_optioninfo_all($opid);
            }else{
                $data['pidArr'] = [];
            }

            $maxKeyid = OptionModel::where(['comid'=>$this->userinfo['comid'],'topid'=>$opid,'deleted_user'=>0])->max('keyid');
            $data['keyid'] = $maxKeyid+1;

            $maxsort = OptionModel::where(['comid'=>$this->userinfo['comid'],'topid'=>$opid,'deleted_user'=>0])->max('sort');
            $data['sort'] = $maxsort+1;
            return outputJson(2000,lang('code_2000'),$data);
        }
    }

    public function addson_option(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['name'])){
                return outputJson(4000, '请输入名称');
            }

            $pidinfo = OptionModel::where(['id'=>$param['id']])->find();

            if((new UserService())->check_option_name($param['name'], $pidinfo['topid'])){
                return outputJson(4000, '名称已存在');
            }
            if(empty($param['keyid'])){
                return outputJson(4000, '请输入键值');
            }
            if((new UserService())->check_option_keyid($param['keyid'], $pidinfo['topid'])){
                return outputJson(4000, '键值已存在');
            }


            $param['pid'] = $pidinfo['id'];
            $param['topid'] = $pidinfo['topid'];

            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');
            unset($param['token']);
            unset($param['id']);

            Db::startTrans();
            try {
                $optionid = OptionModel::insertGetId($param);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'option', $optionid, '基础数据');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data['data'] = OptionModel::where(['id'=>$id])->find();
            $maxKeyid = OptionModel::where(['comid'=>$this->userinfo['comid'],'topid'=>$data['data']['topid']])->max('keyid');
            $data['keyid'] = $maxKeyid+1;


            $maxsort = OptionModel::where(['comid'=>$this->userinfo['comid'],'topid'=>$data['data']['topid'],'deleted_user'=>0])
                ->where(['pid'=>$data['data']['id']])->max('sort');
            $data['sort'] = $maxsort+1;
            return outputJson(2000,lang('code_2000'),$data);
        }
    }

    public function edit_option(Request $request){
        if($request->isPost()){
            $param = $request->post();
            if(empty($param['name'])){
                return outputJson(4000, '请输入名称');
            }

            $pidinfo = OptionModel::where(['id'=>$param['id']])->find();

            if((new UserService())->check_option_name($param['name'], $pidinfo['topid'], $param['id'])){
                return outputJson(4000, '名称已存在');
            }
            if(empty($param['keyid'])){
                return outputJson(4000, '请输入键值');
            }
            if((new UserService())->check_option_keyid($param['keyid'], $pidinfo['topid'], $param['id'])){
                return outputJson(4000, '键值已存在');
            }

            if(empty($param['pid'])){
                $param['pid'] = $pidinfo['topid'];
            }

            $param['comid'] = $this->userinfo['comid'];
            $param['updated_user'] = $this->userinfo['id'];
            $param['updated_at']= date('Y-m-d H:i:s');
            unset($param['token']);

            Db::startTrans();
            try {
                OptionModel::update($param);
                (new OptService())->add_log_list(FlowLogModel::SET_EDIT, 'option', $param['id'], '基础数据');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->get('id',0,'int');
            $data = OptionModel::where(['id'=>$id])->find();
            if($data['topid']){
                $data['pidArr'] = (new UserService())->get_optioninfo_all($data['topid']);
            }else{
                $data['pidArr'] = [];
            }
            return outputJson(2000,lang('code_2000'),$data);
        }
    }

    public function move_option(Request $request){
        if($request->isPost()){
            $id = $request->post('id', 0, 'int');
            $type = $request->post('type', 0, 'int');

            $data = OptionModel::where(['id'=>$id])->find();
            if(!$data){
                return outputJson(2000,lang('code_2000'));
            }

            $list = OptionModel::where(['pid'=>$data['pid'],'topid'=>$data['topid'],'deleted_user'=>0])->order('sort ASC')->column('id');
            if(count($list) < 2){
                return outputJson(2000,lang('code_2000'));
            }

            $info = [];
            if($type == 1){
                foreach ($list as $k=>$opid){
                    if($opid == $data['id']){
                        if($k == 0){
                            $info[] = $opid;
                        }else{
                            $info[$k-1] = $opid;
                            $info[$k] = $list[$k-1];
                        }
                    }else{
                        $info[] = $opid;
                    }
                }
            }elseif($type == 2){
                foreach ($list as $k=>$opid){
                    if($k > 0){
                        if($list[$k-1] == $data['id']){
                            $info[$k-1] = $opid;
                            $info[$k] = $list[$k-1];
                        }else{
                            $info[] = $opid;
                        }
                    }else{
                        $info[] = $opid;
                    }
                }
            }else{
                $info = $list;
            }

            Db::startTrans();
            try {
                $sort = 1;
                foreach ($info as $_opid){
                    OptionModel::where(['id'=>$_opid])->update(['sort'=>$sort]);
                    $sort++;
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(2000,lang('code_2000'));
            }
        }
        return outputJson(2000,lang('code_2000'));
    }

    public function del_option(Request $request){
        $param = $request->post();
        $data = OptionModel::where(['id'=>$param['id']])->find();
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        if( OptionModel::where(['pid'=>$data['id'],'deleted_user'=>0])->find() ){
            return outputJson(4000, '该数据下存在子级数据，不能删除');
        }

        if( $data['isdea'] > 0 ){
            return outputJson(4000, '系统预设数据，不能删除');
        }

        Db::startTrans();
        try {
            OptionModel::where(['id'=>$data['id']])->update([
                'deleted_user'=> $this->userinfo['id'],
                'deleted_at'=> date('Y-m-d H:i:s'),
            ]);
            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'option', $data['id'], '基础数据');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }


    public function list_flow_class(Request $request){
        $param = $request->post();
        $where = [];
        if(isset($param['name']) && !empty($param['name'])){
            $where[] = ['name','like', '%'.$param['name'].'%'];
        }



        $set = FlowSetModel::where($where)->order('sort ASC')->select()->toArray();
        foreach ($set as $key=>&$item){
            $exist = FlowClassModel::where(['comid'=>$this->userinfo['comid'],'setid'=>$item['id']])->find();
            if(!$exist){
                $insid = FlowClassModel::insertGetId(['comid'=>$this->userinfo['comid'], 'setid'=>$item['id'],]);
                $exist = FlowClassModel::where(['id'=>$insid])->find();
            }
            $item['id'] = $exist['id'];
            $item['status'] = $exist['status'];
            if(isset($param['status']) && $param['status'] != ''){
                if($param['status'] != $item['status']){
                    unset($set[$key]);
                    continue;
                }
            }

            $item['lastdt'] = $exist['lastdt'];
            $item['laster_name'] = UserModel::get_realname_by_pk($exist['laster']);
            if(!empty($exist['lastdt'])){
                $item['lastdt'] = "(".date("Y-m-d", strtotime($item['lastdt'])).")";
            }

            $item['ispublish'] = false;
            if(FlowCourseModel::where(['comid'=>$this->userinfo['comid'],'classid'=>$item['id'],'status'=>1,'deleted_user'=>0])->find()){
                $item['ispublish'] = true;
            }
        }

        $list = [];
        $nav = (new UserService())->get_flowset_nav();
        foreach ($nav as $k=>&$v){
            $children = [];
            foreach ($set as $vv){
                if($vv['typename'] == $k){
                    $children[] = $vv;
                }
            }
            if($children){
                $list[] = ['name'=>$v, 'children'=>$children];
            }
        }
        $data['data'] = $list;
//        $data['butauth'] = (new MenuService())->get_butauth('flow_class');
        return outputJson(2000,lang('code_2000'),$data);
    }

    public function status_flow_class(Request $request){
        if($request->isPost()){
            $param = $request->post();

            $class = FlowClassModel::where(['id'=>$param['id']])->find();
            if(!$class){
                return outputJson(4000,lang('code_4000'));
            }

            $newStatus = 1;
            $msg = '启用';
            if($class['status'] > 0){
                $newStatus = 0;
                $msg = '禁用';
            }

            Db::startTrans();
            try {
                FlowClassModel::where(['id'=>$class['id']])->update([
                    'status' => $newStatus,
                    'laster' => $this->userinfo['id'],
                    'lastdt' => date('Y-m-d H:i:s'),
                ]);
                (new OptService())->add_log_list($msg, 'flow_class', $class['id'], '流程配置');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }
        return outputJson(2000,lang('code_2000'));
    }

    public function edit_flow_class(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $old = FlowCourseModel::where(['id'=>$param['id']])->find();
            $param['step'] = json_decode($param['step'], true);

            if(!isset($param['step'][0]['data']['coursetype'])){
                $param['step'][0]['data']['coursetype'] = 0;
            }
            if($param['subtype'] == 3 && $param['step'][0]['data']['coursetype'] != 1){
                $checks = (new UserService())->check_flow_is_rover($param['step']);
                if(!$checks){
                    return outputJson(4000, "发布流程，请设置审核至少一个审核节点");
                }
            }

            if($param['subtype'] == 1){
                Db::startTrans();
                try {
                    FlowCourseModel::where(['id'=>$param['id']])->update([
                        'step'=>json_encode($param['step']),
                        'updated_user'=> $this->userinfo['id'],
                        'updated_at'=> date('Y-m-d H:i:s'),
                    ]);
                    FlowClassModel::where(['id'=>$old['classid']])->update([
                        'lastmid' => $old['id'],
                        'laster' => $this->userinfo['id'],
                        'lastdt' => date('Y-m-d H:i:s'),
                    ]);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return outputJson(4000,lang('code_4000'));
                }
            }

            if($param['subtype'] == 2){
                Db::startTrans();
                try {
                    $newid = FlowCourseModel::where(['id'=>$param['id']])->insertGetId([
                        'comid'=> $this->userinfo['comid'],
                        'classid'=> $old['classid'],
                        'vernum'=> (new UserService())->create_course_vernum($old['classid']),
                        'step'=>json_encode($param['step']),
                        'created_user'=> $this->userinfo['id'],
                        'updated_user'=> $this->userinfo['id'],
                        'created_at'=> date('Y-m-d H:i:s'),
                        'updated_at'=> date('Y-m-d H:i:s'),
                    ]);
                    FlowClassModel::where(['id'=>$old['classid']])->update([
                        'lastmid' => $newid,
                        'laster' => $this->userinfo['id'],
                        'lastdt' => date('Y-m-d H:i:s'),
                    ]);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return outputJson(4000,lang('code_4000'));
                }
            }
            if($param['subtype'] == 3){
                Db::startTrans();
                try {
                    FlowCourseModel::where(['comid'=>$this->userinfo['comid'],'classid'=>$old['classid']])->update([
                        'status'=> 0,
                    ]);
                    FlowCourseModel::where(['id'=>$param['id']])->update([
                        'step'=>json_encode($param['step']),
                        'updated_user'=> $this->userinfo['id'],
                        'updated_at'=> date('Y-m-d H:i:s'),
                        'status'=> 1,
                    ]);
                    FlowClassModel::where(['id'=>$old['classid']])->update([
                        'lastmid' => $old['id'],
                        'laster' => $this->userinfo['id'],
                        'lastdt' => date('Y-m-d H:i:s'),
                    ]);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return outputJson(4000,lang('code_4000'));
                }
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $classid = $request->get('classid', 0, 'int');
            $id = $request->get('id', 0, 'int');
            $class = FlowClassModel::where(['id'=>$classid])->find();
            $set = FlowSetModel::where(['id'=>$class['setid']])->find();
            $factorArr = FlowFactorModel::where(['setid'=>$class['setid']])->select()->toArray();

            if($id > 0){
                $course = FlowCourseModel::where(['id'=>$id])->find();
            }else{
                $course = FlowCourseModel::where(['comid'=>$this->userinfo['comid'],'classid'=>$classid,'deleted_user'=>0])
                    ->order('status DESC')->find();
            }


            if(!$course){
                $course = FlowCourseModel::where(['comid'=>$this->userinfo['comid'],'classid'=>$classid,'deleted_user'=>0])->order('updated_at DESC')->find();
                if(!$course){
                    $couid = (new UserService())->add_default_course($classid);
                    $course = FlowCourseModel::where(['comid'=>$this->userinfo['comid'],'classid'=>$classid,'id'=>$couid,'deleted_user'=>0])->find();
                }
            }

            $list = FlowCourseModel::where(['comid'=>$this->userinfo['comid'],'classid'=>$classid,'deleted_user'=>0])->order('updated_at DESC')->select()->toArray();
            $stepinfo = (new UserService())->put_course_step_info(json_decode($course['step'], true), $factorArr);
            $course['startnode'] = $stepinfo['startnode'];
            $course['steparr'] = $stepinfo['steparr'];
            $data['course'] = $course;
            $data['list'] = $list;
            $data['set'] = $set;

            $startInfo = $stepinfo['startnode']['data'];
            $startInfo['shentype'] = isset($startInfo['shentype']) ? $startInfo['shentype'] : '';
            $startInfo['isadvan'] = isset($startInfo['isadvan']) ? $startInfo['isadvan'] : '';
            $startInfo['coursetype'] = isset($startInfo['coursetype']) ? $startInfo['coursetype'] : '';

            $startInfo['shentype_name'] = '';
            if($startInfo['shentype'] == 'user'){
                $users_name = UserModel::where('id','in',$startInfo['users'])->column('realname');
                $startInfo['shentype_name'] = '用户（'.implode(',',$users_name).'）';
            }elseif($startInfo['shentype'] == 'role'){
                $users_name = UserRoleModel::where('id','in',$startInfo['users'])->column('name');
                $startInfo['shentype_name'] = '角色（'.implode(',',$users_name).'）';
            }elseif($startInfo['shentype'] == 'dept'){
                $users_name = DeptModel::where('id','in',$startInfo['users'])->column('name');
                $startInfo['shentype_name'] = '部门（'.implode(',',$users_name).'）';
            }elseif($startInfo['shentype'] == 'gang'){
                $users_name = UserGangModel::where('id','in',$startInfo['users'])->column('name');
                $startInfo['shentype_name'] = '岗位（'.implode(',',$users_name).'）';
            }else{
                $startInfo['shentype_name'] = '全部人员';
            }
            $startInfo['isadvan_name'] = $startInfo['isadvan'] > 0 ? '是' : '否';
            $startInfo['tonger_name'] = empty($startInfo['tonger']) ? '未设置' : '已设置';
            $startInfo['coursetype_name'] = $startInfo['coursetype'] > 0 ? '自由流程' : '固定流程';

            $data['startInfo'] = $startInfo;
            return outputJson(2000,lang('code_2000'), $data);
        }
    }

    public function assist_flow_class(Request $request){
        if($request->isPost()){
            return outputJson(2000,lang('code_2000'), []);
        }else{
            $classid = $request->get('classid', 0, 'int');
            $users = $request->get('users', '', 'string');
            $shentype = $request->get('shentype', '', 'string');

            if($shentype == 'user'){
                $data['users_info'] = (new UserService())->get_users_part_arr($users, 'user');
            }elseif($shentype == 'dept'){
                $data['users_info'] = (new UserService())->get_users_part_arr($users, 'dept');
            }elseif($shentype == 'role'){
                $data['users_info'] = explode(',', $users);
            }elseif($shentype == 'gang'){
                $data['users_info'] = explode(',', $users);
            }elseif($shentype == 'base'){
                $data['users_info'] = $users;
            }else{
                $data['users_info'] = (new UserService())->get_users_part_arr($users, 'part');
            }

            $class = FlowClassModel::where(['id'=>$classid])->find();
            $data['factor'] = FlowFactorModel::where(['setid'=>$class['setid']])->select()->toArray();
            $data['level'] = (new UserService())->get_flow_term_level();
            $data['conder'] = (new UserService())->get_flow_term_conder();
            $data['shentype'] = (new UserService())->get_flow_shen_type();
            $data['baseArr'] = (new UserService())->get_flow_base();
            $data['gangArr'] = (new UserService())->get_usergang_all();
            $data['roleArr'] = (new UserService())->get_user_roleArr();
            return outputJson(2000,lang('code_2000'), $data);
        }
    }



    public function assist_flow_start_class(Request $request){
        if($request->isPost()){
            return outputJson(2000,lang('code_2000'), []);
        }else{
            $classid = $request->get('classid', 0, 'int');
            $users = $request->get('users', '', 'string');
            $shentype = $request->get('shentype', '', 'string');
            $tonger = $request->get('tonger', '', 'string');

            $data['tonger_info'] = (new UserService())->get_users_part_arr($tonger, 'user');


            $data['users_info'] = [];
            if($shentype == 'user'){
                $data['users_info'] = (new UserService())->get_users_part_arr($users, 'user');
            }elseif($shentype == 'dept'){
                $data['users_info'] = (new UserService())->get_users_part_arr($users, 'dept');
            }elseif($shentype == 'role'){
                $data['users_info'] = explode(',', $users);
            }elseif($shentype == 'gang'){
                $data['users_info'] = explode(',', $users);
            }

            $class = FlowClassModel::where(['id'=>$classid])->find();
            $data['factor'] = FlowFactorModel::where(['setid'=>$class['setid']])->select()->toArray();
            $data['level'] = (new UserService())->get_flow_term_level();
            $data['conder'] = (new UserService())->get_flow_term_conder();
            $data['shentype'] = (new UserService())->get_flow_shen_type_start();
            $data['baseArr'] = (new UserService())->get_flow_base();
            $data['gangArr'] = (new UserService())->get_usergang_all();
            $data['roleArr'] = (new UserService())->get_user_roleArr();
            return outputJson(2000,lang('code_2000'), $data);
        }
    }


    public function del_flow_class(Request $request){
        $param = $request->post();
        $data = FlowCourseModel::where(['id'=>$param['id']])->find();
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        Db::startTrans();
        try {
            FlowCourseModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'flow_course', $data['id'], '流程');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }


    public function list_bill_monitor(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['bill.deleted_user','=', 0];
        $where[] = ['bill.comid','=',$this->userinfo['comid']];
        $where[] = ['bill.isturn','=', 1];

        if(isset($param['sericnum']) && !empty($param['sericnum'])){
            $where[] = ['bill.sericnum','like', '%'.$param['sericnum'].'%'];
        }
        if(isset($param['summary']) && !empty($param['summary'])){
            $where[] = ['bill.summary','like', '%'.$param['summary'].'%'];
        }
        if(isset($param['enginame']) && !empty($param['enginame'])){
            $where[] = ['bill.enginame','like', '%'.$param['enginame'].'%'];
        }
        if(isset($param['created_user']) && !empty($param['created_user'])){
            $where[] = ['user.realname','like', '%'.$param['created_user'].'%'];
        }
        if(isset($param['modeid']) && !empty($param['modeid'])){
            $where[] = ['bill.modeid','=', $param['modeid']];
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['bill.status','=', $param['status']];
        }
        if(isset($param['created_at']) && !empty($param['created_at'])){
            $seadt = explode(' - ', $param['created_at']);
            $where[] = ['bill.created_at','between', [$seadt[0].' 00:00:00', $seadt[1].' 23:59:59']];
        }


        $data['data'] = FlowBillModel::alias('bill')
            ->field('bill.*,user.realname as created_user_name')
            ->join('user user','user.id=bill.created_user')
            ->where($where)
            ->order('bill.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['status_name'] = (new FlowService())->get_flow_flowtext($item);
                return $item;
            })->toArray();


        $data['statusArr'] = (new FlowService())->get_flow_status();
        $data['is_status'] = isset($param['status']) ? $param['status'] : '';
        $data['modeidArr'] = (new FlowService())->get_flow_modename();
        return outputJson(2000,lang('code_2000'),$data);
    }

    public function list_bill_strange(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['bill.deleted_user','=', 0];
        $where[] = ['bill.comid','=',$this->userinfo['comid']];
        $where[] = ['bill.isturn','=', 1];
        $where[] = ['bill.status','=', 0];

        if(isset($param['sericnum']) && !empty($param['sericnum'])){
            $where[] = ['bill.sericnum','like', '%'.$param['sericnum'].'%'];
        }
        if(isset($param['summary']) && !empty($param['summary'])){
            $where[] = ['bill.summary','like', '%'.$param['summary'].'%'];
        }
        if(isset($param['enginame']) && !empty($param['enginame'])){
            $where[] = ['bill.enginame','like', '%'.$param['enginame'].'%'];
        }
        if(isset($param['created_user']) && !empty($param['created_user'])){
            $where[] = ['user.realname','like', '%'.$param['created_user'].'%'];
        }
        if(isset($param['modeid']) && !empty($param['modeid'])){
            $where[] = ['bill.modeid','=', $param['modeid']];
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['bill.status','=', $param['status']];
        }
        if(isset($param['created_at']) && !empty($param['created_at'])){
            $seadt = explode(' - ', $param['created_at']);
            $where[] = ['bill.created_at','between', [$seadt[0].' 00:00:00', $seadt[1].' 23:59:59']];
        }

        $list = [];
        $billinfo = FlowBillModel::alias('bill')
            ->field('bill.*,user.realname as created_user_name')
            ->join('user user','user.id=bill.created_user')
            ->where($where)
            ->order('bill.id DESC')
            ->select()->toArray();

        foreach ($billinfo as $item){
            $strange = (new FlowService())->get_flow_flowtext_strange($item);
            if($strange){
                $item['status_name'] = '<span class="mindianhong"></span>进行中(流程异常)';
                $list[] = $item;
            }
        }


        $data['data'] = $list;
        $data['statusArr'] = (new FlowService())->get_flow_status();
        $data['is_status'] = isset($param['status']) ? $param['status'] : '';
        $data['modeidArr'] = (new FlowService())->get_flow_modename();
        return outputJson(2000,lang('code_2000'),$data);
    }

    public function list_bill_tong(Request $request){
        $param = $request->post();
        get_page($param);

        $where = [];
        if(isset($param['modeid']) && !empty($param['modeid'])){
            $where[] = ['id','=', $param['modeid']];
        }

        $where22 = [];
        $where22[] = ['comid','=', $this->userinfo['comid']];
        $where22[] = ['deleted_user','=', 0];
        if(isset($param['created_at']) && !empty($param['created_at'])){
            $seadt = explode(' - ', $param['created_at']);
            $start = $seadt[0].'-01 00:00:00';
            $end = date('Y-m-d 23:59:59', strtotime('last day of', strtotime($seadt[1].'-01 00:00:00')));
            $where22[] = ['created_at','between', [$start, $end]];
        }

        $set = FlowSetModel::field('id,name')->where($where)->order('typename ASC,sort ASC')->select()->toArray();
        foreach ($set as &$item){
            $item['zong'] = FlowBillModel::where($where22)->where(['modeid'=>$item['id']])->count();
            $item['shen'] = FlowBillModel::where($where22)->where(['modeid'=>$item['id'],'isturn'=>1,'status'=>0])->count();
            $item['shen_tong'] = FlowBillModel::where($where22)->where(['modeid'=>$item['id'],'isturn'=>1,'status'=>1])->count();
            $item['shen_butong'] = FlowBillModel::where($where22)->where(['modeid'=>$item['id'],'isturn'=>1,'status'=>2])->count();
            $item['shen_end'] = FlowBillModel::where($where22)->where(['modeid'=>$item['id'],'isturn'=>1,'status'=>3])->count();
            $item['shen_fei'] = FlowBillModel::where($where22)->where(['modeid'=>$item['id'],'isturn'=>1,'status'=>5])->count();
        }

        $data['data'] = $set;
        $data['modeidArr'] = (new FlowService())->get_flow_modename();
        $data['is_modeid'] = isset($param['modeid']) ? $param['modeid'] : '';
        return outputJson(2000,lang('code_2000'),$data);
    }


    public function list_bill_dao(Request $request){
        $param = $request->post();
        get_page($param);
        $data = [];

        $where = [];
        if(isset($param['keyword']) && !empty($param['keyword'])){
            $where[] = ['bill.modename','like', '%'.$param['keyword'].'%'];
        }

        if($param['typess'] == 'bill_create'){
            $data = FlowBillModel::alias('bill')
                ->field('bill.modeid as id,bill.modename as title,count(bill.modeid) as num')
                ->where(['bill.deleted_user'=>0])
                ->where(['bill.comid'=>$this->userinfo['comid']])
                ->where(['bill.created_user'=>$this->userinfo['id']])
                ->where(['bill.isturn'=>1])
                ->where($where)
                ->group('bill.modeid')
                ->paginate($param['pagesize'],false,['page'=>$param['page']])
                ->each(function ($item,$key){
                    return $item;
                })->toArray();
        }

        if($param['typess'] == 'bill_hand'){
            $data = FlowBillModel::alias('bill')
                ->field('bill.modeid as id,bill.modename as title,count(bill.modeid) as num')
                ->where(['bill.deleted_user'=>0])
                ->where(['bill.comid'=>$this->userinfo['comid']])
                ->where(['bill.created_user'=>$this->userinfo['id']])
                ->where(['bill.isturn'=>1])
                ->where(['bill.status'=>0])
                ->where($where)
                ->group('bill.modeid')
                ->paginate($param['pagesize'],false,['page'=>$param['page']])
                ->each(function ($item,$key){
                    return $item;
                })->toArray();
        }

        if($param['typess'] == 'bill_finish'){
            $data = FlowBillModel::alias('bill')
                ->field('bill.modeid as id,bill.modename as title,count(bill.modeid) as num')
                ->where(['bill.deleted_user'=>0])
                ->where(['bill.comid'=>$this->userinfo['comid']])
                ->where(['bill.created_user'=>$this->userinfo['id']])
                ->where(['bill.isturn'=>1])
                ->where('bill.status','in',[1,2,3,5])
                ->where($where)
                ->group('bill.modeid')
                ->paginate($param['pagesize'],false,['page'=>$param['page']])
                ->each(function ($item,$key){
                    return $item;
                })->toArray();
        }

        if($param['typess'] == 'bill_turn'){
            $data = FlowBillModel::alias('bill')
                ->field('bill.modeid as id,bill.modename as title,count(bill.modeid) as num')
                ->where(['bill.deleted_user'=>0])
                ->where(['bill.comid'=>$this->userinfo['comid']])
                ->where(['bill.created_user'=>$this->userinfo['id']])
                ->where(['bill.isturn'=>0])
                ->where($where)
                ->group('bill.modeid')
                ->paginate($param['pagesize'],false,['page'=>$param['page']])
                ->each(function ($item,$key){
                    return $item;
                })->toArray();
        }

        if($param['typess'] == 'bill_share'){
            $whereShare = Db::raw("share.uid=".$this->userinfo['id']." or find_in_set(".$this->userinfo['id'].",domer)");
            $data = FlowShareModel::alias('share')
                ->field('bill.modeid as id,bill.modename as title,count(bill.modeid) as num')
                ->leftJoin('flow_bill bill','share.billid = bill.id')
                ->where(['bill.deleted_user'=>0])
                ->where(['bill.comid'=>$this->userinfo['comid']])
                ->where(['bill.isturn'=>1])
                ->where($where)
                ->where($whereShare)
                ->group('bill.modeid')
                ->paginate($param['pagesize'],false,['page'=>$param['page']])
                ->each(function ($item,$key){
                    return $item;
                })->toArray();
        }

        if($param['typess'] == 'flow_hand'){
            $data = FlowTaskModel::alias('task')
                ->field('bill.modeid as id,bill.modename as title,count(bill.modeid) as num')
                ->join('flow_bill bill','bill.id=task.billid')
                ->where(['bill.deleted_user'=>0])
                ->where(['bill.comid'=>$this->userinfo['comid']])
                ->where(['bill.isturn'=>1])
                ->where(['bill.status'=>0])
                ->where(['task.deleted_user'=>0])
                ->where(['task.uid'=>$this->userinfo['id']])
                ->where(['task.state'=>1])
                ->where($where)
                ->group('bill.modeid')
                ->paginate($param['pagesize'],false,['page'=>$param['page']])
                ->each(function ($item,$key){
                    return $item;
                })->toArray();
        }

        if($param['typess'] == 'flow_finish'){
            $data = FlowTaskShenModel::alias('shen')
                ->field('bill.modeid as id,bill.modename as title,count(bill.modeid) as num')
                ->join('flow_bill bill','bill.id=shen.billid')
                ->where(['bill.deleted_user'=>0])
                ->where(['bill.comid'=>$this->userinfo['comid']])
                ->where(['bill.isturn'=>1])
                ->where(['shen.uid'=>$this->userinfo['id']])
                ->where($where)
                ->group('bill.modeid')
                ->paginate($param['pagesize'],false,['page'=>$param['page']])
                ->each(function ($item,$key)use($where){
                    $item['num'] = FlowTaskShenModel::alias('shen')
                        ->join('flow_bill bill','bill.id=shen.billid')
                        ->where(['bill.deleted_user'=>0])
                        ->where(['bill.comid'=>$this->userinfo['comid']])
                        ->where(['bill.isturn'=>1])
                        ->where(['bill.modeid'=>$item['id']])
                        ->where(['shen.uid'=>$this->userinfo['id']])
                        ->where($where)
                        ->group('bill.id')->count();
                    return $item;
                })->toArray();
        }

        if($param['typess'] == 'flow_promer'){
            $wherePromer = Db::raw("promer.uid=".$this->userinfo['id']." or find_in_set(".$this->userinfo['id'].",domer)");
            $data = FlowPromerModel::alias('promer')
                ->field('bill.modeid as id,bill.modename as title,count(bill.modeid) as num')
                ->join('flow_bill bill','promer.billid = bill.id')
                ->where(['bill.deleted_user'=>0])
                ->where(['bill.comid'=>$this->userinfo['comid']])
                ->where(['bill.created_user'=>$this->userinfo['id']])
                ->where(['bill.isturn'=>1])
                ->where($where)
                ->where($wherePromer)
                ->group('bill.modeid')
                ->paginate($param['pagesize'],false,['page'=>$param['page']])
                ->each(function ($item,$key){
                    return $item;
                })->toArray();
        }

        return outputJson(2000,lang('code_2000'),$data);
    }









    public function list_user_take(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['take.deleted_user','=', 0];
        $where[] = ['take.comid','=',$this->userinfo['comid']];

        if(isset($param['jiaoer_name']) && !empty($param['jiaoer_name'])){
            $where[] = ['jiao.realname','like', '%'.$param['jiaoer_name'].'%'];
        }
        if(isset($param['jieer_name']) && !empty($param['jieer_name'])){
            $where[] = ['jie.realname','like', '%'.$param['jieer_name'].'%'];
        }

        if(isset($param['type']) && !empty($param['type'])){
            $where[] = ['take.type','=', $param['type']];
        }


        $data['type'] = (new UserService())->get_user_take_type();
        $data['is_type'] = isset($param['type']) ? $param['type'] : '';


        $data['data'] = UserTakeModel::alias('take')
            ->field('take.*,jiao.realname as jiaoer_name,jie.realname as jieer_name')
            ->join('user jiao','jiao.id=take.jiaoer')
            ->join('user jie','jie.id=take.jieer')
            ->where($where)
            ->order('take.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['type_name'] = (new UserService())->get_user_take_type_name($item['type']);
                $item['shi_name'] = (new UserService())->get_user_take_shi_name($item['shi']);
                $item['created_user_name'] = UserModel::get_realname_by_pk($item['created_user']);
                return $item;
            })->toArray();

        $data['butauth'] = (new MenuService())->get_butauth('user_take');
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function add_user_take(Request $request){
        if($request->isPost()){
            $param = $request->post();

            if(empty($param['type'])){
                return outputJson(4000, '请选择交接类型');
            }
            if(empty($param['jiaoer'])){
                return outputJson(4000, '请选择交接人');
            }
            if(empty($param['jieer'])){
                return outputJson(4000, '请选择接手人');
            }
            if(empty($param['shi'])){
                return outputJson(4000, '请选择交接事项');
            }
            if(empty($param['con'])){
                return outputJson(4000, '请选择交接内容');
            }



            $param['comid'] = $this->userinfo['comid'];
            $param['created_user'] = $param['updated_user'] = $this->userinfo['id'];
            $param['created_at'] = $param['updated_at']= date('Y-m-d H:i:s');

            $files = array_filter($param['files']);
            unset($param['files']);
            unset($param['token']);


            $jiaoerName = UserModel::get_realname_by_pk($param['jiaoer']);
            $jieerName = UserModel::get_realname_by_pk($param['jieer']);
            $jiaoExplain = $jiaoerName.'交接至'.$jieerName;


            Db::startTrans();
            try {
                $takeid = UserTakeModel::insertGetId($param);
                if($param['isting'] > 0){
                    UserModel::where(['id'=>$param['jiaoer']])->update(['status'=>0]);
                }

                $conarr = explode(',', $param['con']);
                if($param['shi'] == 'qing_all'){
                    foreach ($conarr as $v){
                        $hand = FlowBillModel::field('modenum,modename,count(modenum) as num
                        ,GROUP_CONCAT(id) as idstr,GROUP_CONCAT(mid) as midstr')
                            ->where(['deleted_user'=>0,'comid'=>$this->userinfo['comid']])
                            ->where(['created_user'=>$this->userinfo['id'],'isturn'=>1])
                            ->where('status','in',[0,1,2])
                            ->where(['modenum'=>$v])
                            ->select()->toArray();
                        foreach ($hand as $vvv){
                            $idstr = explode(',',$vvv['idstr']);
                            $midstr = explode(',',$vvv['midstr']);
                            foreach($idstr as $id_k => $id_v){
                                $updModenum = $vvv['modenum'];
                                if($vvv['modenum'] == 'cert_user_bid'){
                                    $updModenum = 'cert_user';
                                }
                                FlowBillModel::where(['id'=>$idstr[$id_k]])->update(['created_user'=>$param['jieer'],'flowuser'=>$jieerName]);
                                Db::name($updModenum)->where(['id'=>$midstr[$id_k]])->update(['created_user'=>$param['jieer'],'flowuser'=>$jieerName]);
                                (new OptService())->add_flow_shenlog(['billid'=>$id_v,'name'=>$vvv['modename']],'流程申请人交接',$this->userinfo['realname'],$jiaoExplain);
                            }
                            $vvv['takeid'] = $takeid;
                            UserTakeListModel::insert($vvv);
                        }
                    }
                }
                if($param['shi'] == 'qing_shen'){
                    foreach ($conarr as $v){
                        $hand = FlowBillModel::field('modenum,modename,count(modenum) as num
                        ,GROUP_CONCAT(id) as idstr,GROUP_CONCAT(mid) as midstr')
                            ->where(['deleted_user'=>0,'comid'=>$this->userinfo['comid']])
                            ->where(['created_user'=>$this->userinfo['id'],'isturn'=>1])
                            ->where('status','=',0)
                            ->where(['modenum'=>$v])
                            ->select()->toArray();
                        foreach ($hand as $vvv){
                            $idstr = explode(',',$vvv['idstr']);
                            $midstr = explode(',',$vvv['midstr']);
                            foreach($idstr as $id_k => $id_v){
                                $updModenum = $vvv['modenum'];
                                if($vvv['modenum'] == 'cert_user_bid'){
                                    $updModenum = 'cert_user';
                                }
                                FlowBillModel::where(['id'=>$idstr[$id_k]])->update(['created_user'=>$param['jieer'],'flowuser'=>$jieerName]);
                                Db::name($updModenum)->where(['id'=>$midstr[$id_k]])->update(['created_user'=>$param['jieer'],'flowuser'=>$jieerName]);
                                (new OptService())->add_flow_shenlog(['billid'=>$id_v,'name'=>$vvv['modename']],'流程申请人交接',$this->userinfo['realname'],$jiaoExplain);
                            }
                            $vvv['takeid'] = $takeid;
                            UserTakeListModel::insert($vvv);
                        }
                    }
                }
                if($param['shi'] == 'pi_all'){
                    foreach ($conarr as $v){
                        $hand = FlowTaskModel::alias('task')
                            ->field('bill.modenum,bill.modename,count(bill.modenum) as num,GROUP_CONCAT(task.id) as taskidstr
                            ,GROUP_CONCAT(bill.id) as idstr,GROUP_CONCAT(bill.mid) as midstr')
                            ->join('flow_bill bill','bill.id=task.billid')
                            ->where(['bill.deleted_user'=>0,'bill.comid'=>$this->userinfo['comid']])
                            ->where(['task.uid'=>$this->userinfo['id'],'bill.isturn'=>1])
                            ->where(['bill.status'=>0,'task.state'=>1])
                            ->where(['modenum'=>$v])
                            ->group('bill.modenum')
                            ->select()->toArray();

                        foreach ($hand as $vvv){
                            $idstr = explode(',',$vvv['idstr']);
                            $taskidstr = explode(',',$vvv['taskidstr']);
                            foreach($taskidstr as $id_k => $id_v){
                                $stepStr = FlowBillModel::where(['id'=>$idstr[$id_k]])->value('step');
                                $newStep = $this->replace_jiaoer_or_jieer($stepStr, $param['jiaoer'], $param['jieer']);
                                FlowBillModel::where(['id'=>$idstr[$id_k]])->update(['step'=>$newStep]);

                                FlowTaskModel::where(['id'=>$id_v])->update(['uid'=>$param['jieer']]);
                                (new OptService())->add_flow_shenlog(['billid'=>$idstr[$id_k],'name'=>$vvv['modename']],'流程审批人交接',$this->userinfo['realname'],$jiaoExplain);
                            }
                            unset($vvv['taskidstr']);
                            $vvv['takeid'] = $takeid;
                            UserTakeListModel::insert($vvv);
                        }
                    }

                    foreach ($conarr as $v){
                        $setid = FlowSetModel::where(['modenum'=>$v])->value('id');
                        $clssid = FlowClassModel::where(['comid'=>$this->userinfo['comid'],'setid'=>$setid,'status'=>1])->value('id');
                        $course = FlowCourseModel::where(['comid'=>$this->userinfo['comid'],'classid'=>$clssid,'status'=>1])->find();
                        if($course){
                            $newStep = $this->replace_jiaoer_or_jieer($course['step'], $param['jiaoer'], $param['jieer']);
                            FlowCourseModel::where(['id'=>$course['id']])->update(['step'=>$newStep]);
                        }
                    }
                }
                if($param['shi'] == 'pi_pei'){
                    foreach ($conarr as $v){
                        $setid = FlowSetModel::where(['modenum'=>$v])->value('id');
                        $clssid = FlowClassModel::where(['comid'=>$this->userinfo['comid'],'setid'=>$setid,'status'=>1])->value('id');
                        $course = FlowCourseModel::where(['comid'=>$this->userinfo['comid'],'classid'=>$clssid,'status'=>1])->find();
                        if($course){
                            $newStep = $this->replace_jiaoer_or_jieer($course['step'], $param['jiaoer'], $param['jieer']);
                            FlowCourseModel::where(['id'=>$course['id']])->update(['step'=>$newStep]);
                        }
                    }
                }
                if($param['shi'] == 'pi_shen'){
                    foreach ($conarr as $v){
                        $hand = FlowTaskModel::alias('task')
                            ->field('bill.modenum,bill.modename,count(bill.modenum) as num,GROUP_CONCAT(task.id) as taskidstr
                            ,GROUP_CONCAT(bill.id) as idstr,GROUP_CONCAT(bill.mid) as midstr')
                            ->join('flow_bill bill','bill.id=task.billid')
                            ->where(['bill.deleted_user'=>0,'bill.comid'=>$this->userinfo['comid']])
                            ->where(['task.uid'=>$this->userinfo['id'],'bill.isturn'=>1])
                            ->where(['bill.status'=>0,'task.state'=>1])
                            ->where(['modenum'=>$v])
                            ->group('bill.modenum')
                            ->select()->toArray();

                        foreach ($hand as $vvv){
                            $idstr = explode(',',$vvv['idstr']);
                            $taskidstr = explode(',',$vvv['taskidstr']);
                            foreach($taskidstr as $id_k => $id_v){
                                $stepStr = FlowBillModel::where(['id'=>$idstr[$id_k]])->value('step');
                                $newStep = $this->replace_jiaoer_or_jieer($stepStr, $param['jiaoer'], $param['jieer']);
                                FlowBillModel::where(['id'=>$idstr[$id_k]])->update(['step'=>$newStep]);

                                FlowTaskModel::where(['id'=>$id_v])->update(['uid'=>$param['jieer']]);
                                (new OptService())->add_flow_shenlog(['billid'=>$idstr[$id_k],'name'=>$vvv['modename']],'流程审批人交接',$this->userinfo['realname'],$jiaoExplain);
                            }
                            unset($vvv['taskidstr']);
                            $vvv['takeid'] = $takeid;
                            UserTakeListModel::insert($vvv);
                        }
                    }
                }

                (new OptService())->relation_file($files,'user_take',$takeid);
                (new OptService())->add_flow_log(FlowLogModel::SET_ADD, 'user_take', $takeid);
                (new OptService())->add_log_list(FlowLogModel::SET_ADD, 'user_take', $takeid, '人员交接');
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,$e->getMessage());
                return outputJson(4000,lang('code_4000'));
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $data['typearr'] = (new UserService())->get_user_take_type();
            $data['qingarr'] = (new UserService())->get_user_take_qing();
            $data['piarr'] = (new UserService())->get_user_take_pi();
            return outputJson(2000,lang('code_2000'), $data);
        }
    }
    public function show_user_take(Request $request){
        $id = $request->post('id', 0, 'int');
        $data = UserTakeModel::get_info_by_pk($id);
        if(!$data){
            return outputJson(4000, lang('code_4000'));
        }


        $con_name = FlowSetModel::where('modenum','in',$data['con'])->column('name');
        $data['con_name'] = implode('，',$con_name);

        $list = UserTakeListModel::where(['takeid'=>$data['id']])->select()->toArray();
        $data['list'] = $list;

        $data['isting_name'] = $data['isting'] > 0 ? '是' : '否';
        $data['jiaoer_name'] = UserModel::get_realname_by_pk($data['jiaoer']);
        $data['jieer_name'] = UserModel::get_realname_by_pk($data['jieer']);
        $data['type_name'] = (new UserService())->get_user_take_type_name($data['type']);
        $data['shi_name'] = (new UserService())->get_user_take_shi_name($data['shi']);
        $data['created_user_name'] = UserModel::get_realname_by_pk($data['created_user']);
        $data['files'] = (new OptService())->get_file('user_take', $data['id']);
        return outputJson(2000,lang('code_2000'), $data);
    }
    public function del_user_take(Request $request){
        $param = $request->post();
        $data = UserTakeModel::get_info_by_pk($param['id']);
        if(!$data){
            return outputJson(4000,lang('code_4000'));
        }

        Db::startTrans();
        try {
            UserTakeModel::where(['id'=>$data['id']])->update([
                'deleted_user' => $this->userinfo['id'],
                'deleted_at' => date('Y-m-d H:i:s')
            ]);
            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, 'user_take', $data['id'], '人员交接');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }
        return outputJson(2000,lang('code_2000'));
    }
    public function shi_user_take(Request $request){
        $param = $request->post();
        if(empty($param['jiaoer']) || empty($param['shi'])){
            return outputJson(2000,lang('code_2000'), []);
        }
        $data = [];

        if($param['shi'] == 'qing_all'){
            $data = FlowBillModel::field('modenum,modename,count(modenum) as num')
                ->where(['deleted_user'=>0,'comid'=>$this->userinfo['comid']])
                ->where(['created_user'=>$this->userinfo['id'],'isturn'=>1])
                ->where('status','in',[0,1,2])
                ->order('num DESC')
                ->group('modenum')
                ->select()->toArray();
            foreach ($data as &$item){
                $item['value'] = $item['modenum'];
                $item['name'] = $item['modename'].'('.$item['num'].')';
            }
        }

        if($param['shi'] == 'qing_shen'){
            $data = FlowBillModel::field('modenum,modename,count(modenum) as num')
                ->where(['deleted_user'=>0,'comid'=>$this->userinfo['comid']])
                ->where(['created_user'=>$this->userinfo['id'],'isturn'=>1])
                ->where(['status'=>0])
                ->order('num DESC')
                ->group('modenum')
                ->select()->toArray();
            foreach ($data as &$item){
                $item['value'] = $item['modenum'];
                $item['name'] = $item['modename'].'('.$item['num'].')';
            }
        }

        if($param['shi'] == 'pi_all'){
            $onarr = FlowTaskModel::alias('task')
                ->field('bill.modenum,bill.modename,count(bill.modenum) as num')
                ->join('flow_bill bill','bill.id=task.billid')
                ->where(['bill.deleted_user'=>0,'bill.comid'=>$this->userinfo['comid']])
                ->where(['task.uid'=>$this->userinfo['id'],'bill.isturn'=>1])
                ->where(['bill.status'=>0,'task.state'=>1])
                ->order('num DESC')
                ->group('bill.modenum')
                ->select()->toArray();

            $data = FlowSetModel::field('modenum,name as modename')->order('typename ASC,sort ASC')->select()->toArray();
            foreach ($data as &$item){
                $item['value'] = $item['modenum'];
                $item['name'] = $item['modename'];
                foreach ($onarr as $vv){
                    if($vv['modenum'] == $item['modenum']){
                        $item['name'] = $vv['modename'].'('.$vv['num'].')';
                    }
                }
            }
        }

        if($param['shi'] == 'pi_pei'){
            $data = FlowSetModel::field('modenum,name as modename')->select()->toArray();
            foreach ($data as &$item){
                $item['value'] = $item['modenum'];
                $item['name'] = $item['modename'];
            }
        }

        if($param['shi'] == 'pi_shen'){
            $data = FlowTaskModel::alias('task')
                ->field('bill.modenum,bill.modename,count(bill.modenum) as num')
                ->join('flow_bill bill','bill.id=task.billid')
                ->where(['bill.deleted_user'=>0,'bill.comid'=>$this->userinfo['comid']])
                ->where(['task.uid'=>$this->userinfo['id'],'bill.isturn'=>1])
                ->where(['bill.status'=>0,'task.state'=>1])
                ->order('num DESC')
                ->group('bill.modenum')
                ->select()->toArray();
            foreach ($data as &$item){
                $item['value'] = $item['modenum'];
                $item['name'] = $item['modename'].'('.$item['num'].')';
            }
        }


        return outputJson(2000,lang('code_2000'), $data);
    }
    public function detail_user_take(Request $request){
        $param = $request->post();
        get_page($param);

        $where[] = ['bill.deleted_user','=', 0];
        $where[] = ['bill.comid','=',$this->userinfo['comid']];
        $where[] = ['bill.isturn','=', 1];
        $where[] = ['bill.id','in', $param['idstr']];

        if(isset($param['sericnum']) && !empty($param['sericnum'])){
            $where[] = ['bill.sericnum','like', '%'.$param['sericnum'].'%'];
        }
        if(isset($param['summary']) && !empty($param['summary'])){
            $where[] = ['bill.summary','like', '%'.$param['summary'].'%'];
        }
        if(isset($param['enginame']) && !empty($param['enginame'])){
            $where[] = ['bill.enginame','like', '%'.$param['enginame'].'%'];
        }
        if(isset($param['created_user']) && !empty($param['created_user'])){
            $where[] = ['user.realname','like', '%'.$param['created_user'].'%'];
        }
        if(isset($param['status']) && $param['status'] != ''){
            $where[] = ['bill.status','=', $param['status']];
        }
        if(isset($param['created_at']) && !empty($param['created_at'])){
            $seadt = explode(' - ', $param['created_at']);
            $where[] = ['bill.created_at','between', [$seadt[0].' 00:00:00', $seadt[1].' 23:59:59']];
        }

        $data['data'] = FlowBillModel::alias('bill')
            ->field('bill.*,user.realname as created_user_name')
            ->join('user user','user.id=bill.created_user')
            ->where($where)
            ->order('bill.id DESC')
            ->paginate($param['pagesize'],false,['page'=>$param['page']])
            ->each(function ($item,$key){
                $item['status_name'] = (new FlowService())->get_flow_flowtext($item);
                return $item;
            })->toArray();

        $data['statusArr'] = (new FlowService())->get_flow_status();
        $data['is_status'] = isset($param['status']) ? $param['status'] : '';
        return outputJson(2000,lang('code_2000'),$data);
    }
    public function replace_jiaoer_or_jieer($step, $jiaoer, $jieer){
        $data = json_decode($step, true);
        if(!$data || !is_array($data)){
            return $step;
        }
        $data = $this->replace_datas($data, $jiaoer, $jieer);
        return json_encode($data);
    }
    public function replace_datas($data, $jiaoer, $jieer){
        foreach ($data as &$item){
            if($item['node'] == 'rover'){
                if($item['data']['shentype'] == 'user'){
                    $users = explode(',', $item['data']['users']);
                    foreach ($users as $kk=>$vv){
                        if($vv == $jiaoer){
                            $users[$kk] = $jieer;
                        }
                    }
                    $item['data']['users'] = implode(',', array_unique($users));
                }
            }
            if($item['node'] == 'term'){
                foreach ($item['data'] as &$itemTerm){
                    if(isset($itemTerm['children'])){
                        $itemTerm['children'] = $this->replace_datas($itemTerm['children'], $jiaoer, $jieer);
                    }
                }
            }
        }
        return $data;
    }




}
